#!/usr/bin/python
# coding:utf-8

import os
import shutil
import time

_root = os.path.abspath(os.path.dirname(__file__)).replace('\\', '/')
# 打包用
# _root = os.path.dirname(os.path.realpath(sys.executable))

_basePath = _root + "/pb/proto"


# 需要转换的语言
languageList = [
    "go",
    "python",
    "js",
]

# 生成python.go存放目录
if "python" in languageList:
    _chkFolder = _root + "/pb/pb_python"
    if os.path.exists(_chkFolder):
        shutil.rmtree(_chkFolder)
    os.mkdir(_chkFolder)
    with open(f"{_chkFolder}/__init__.py", "w") as f:
        f.write(" ")


# 命令执行
def command(base_path, go_out_path, folder, file):
    _dir = f"{base_path}/{folder}"
    for language in languageList:
        _command = None
        if language == "go":
            _importPath = f"{base_path}/{folder}/{file}" if folder else f"{base_path}/{file}"
            _command = f"protoc --proto_path={base_path} --go_out={go_out_path} --go_opt=paths=import {_importPath}"
            # print(_command)
        elif language == "python":
            # 生成init文件变为可导入
            _chkFolder = f"{go_out_path}/pb_python/{folder}"
            if os.path.exists(_chkFolder):
                shutil.rmtree(_chkFolder)
            os.mkdir(_chkFolder)
            with open(f"{_chkFolder}/__init__.py", "w") as f:
                f.write(" ")

            _command = f"protoc_python --proto_path={base_path} --{language}_out={go_out_path}/pb_{language} {base_path}/{folder}/*.proto"
        elif language == "js":
            _command = f"protoc_python --proto_path={base_path} --{language}_out=import_style=commonjs,binary:{go_out_path}/pb_{language} {base_path}/{folder}/*.proto"

        if _command:
            os.system(_command)
            print(f"{folder}【{file}】转换【{language}】成功")


# 是否是pb文件
def isPBFile(path, file):
    if ".proto" not in file:
        return False

    _filePath = f"{path}/{file}"
    # 文件不能为空
    if not os.path.getsize(_filePath):
        print(f"{_filePath}不能为空!!!!!!!!!!!!!!!!!!")
        return False

    return True


# 修改api文件导包路径
def updateFromPath():
    _chkFolder = f"{_root}/pb/pb_python"
    if not os.path.exists(_chkFolder):
        return

    _folderList = os.listdir(_chkFolder)
    _contentList = []
    _fileNameList = []
    for folder in _folderList:
        _toPath = _chkFolder + "/" + folder
        # 不是文件夹
        if not os.path.isdir(_toPath):
            continue

        _fileList = os.listdir(_toPath)
        # 当前目录下没有文件
        if not _fileList:
            continue

        for file in _fileList:
            # 不是api文件
            if "api" not in file:
                continue

            _filePath = f"{_toPath}/{file}"
            _fileContent = ""
            with open(_filePath, "r", encoding="utf-8") as f:
                _fileContent = f.read()

            _chkStr = f'from {folder}'
            if _chkStr not in _fileContent:
                continue

            _fileContent = _fileContent.replace(_chkStr, f'from pb.pb_python.{folder}')

            with open(_filePath, "w", encoding="utf-8") as f:
                    f.write(_fileContent)


# 生成export.js
def createExportJs():
    _jsPbPath = f"{_root}/pb/pb_js"
    _folderList = os.listdir(_jsPbPath)
    # 当前目录下没有文件
    if not _folderList:
        return

    _contentList = []
    _fileNameList = []
    for folder in _folderList:
        _toPath = _jsPbPath + "/" + folder
        # 不是文件夹
        if not os.path.isdir(_toPath):
            continue

        _fileList = os.listdir(_toPath)
        # 当前目录下没有文件
        if not _fileList:
            continue

        for file in _fileList:
            # 不是js文件
            if ".js" not in file:
                continue

            _fileName = file.split(".js")[0]
            _fileNameList.append(_fileName)
            _contentList.append(f'var {_fileName} = require("./pb/pb_js/{folder}/{_fileName}")\n')

    _contentList.append("\nmodule.exports = {\n")
    for fileName in _fileNameList:
        _contentList.append(f"    {fileName}: {fileName},\n")
    _contentList.append("}")

    with open(_root + "/exports.js", "w") as f:
        f.writelines(_contentList)

    try:
        os.system("browserify exports.js -o pb_js.js")
    except:
        pass


def pb2go():
    _insertList = []

    _folderList = os.listdir(_basePath)

    _goOutPath = _root + "/pb"
    for folder in _folderList:
        _toPath = _basePath + "/" + folder
        # 是文件夹
        if os.path.isdir(_toPath):
            _fileList = os.listdir(_toPath)
            # 当前目录下没有文件
            if not _fileList:
                continue

            for file in _fileList:
                # 不是pb文件
                if not isPBFile(_toPath, file):
                    continue
                command(_basePath, _goOutPath, folder, file)
        # pb文件
        else:
            if isPBFile(_basePath, folder):
                command(_basePath, _goOutPath, "", folder)

    if "js" in languageList:
        createExportJs()

    if "python" in languageList:
        updateFromPath()


    # time.sleep(5)


if __name__ == '__main__':
    pb2go()
    createExportJs()